//
//  MyMoodViewController.m
//  SunXi
//
//  Created by dllo on 15/11/30.
//  Copyright © 2015年 大远. All rights reserved.
//

#import "MyMoodViewController.h"

@interface MyMoodViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain) UITableView *tableView;

@property(nonatomic, retain) CoreDataManager *manager;

@end

@implementation MyMoodViewController{
    UIView *_nilview;
}

- (void)viewDidAppear:(BOOL)animated {
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"WriteMood"];
    
    NSError *error;
    self.writeArr = [NSMutableArray arrayWithArray:[self.manager.managedObjectContext executeFetchRequest:request error:&error]];
    [self.tableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIImageView *imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"drawBackPic.jpg"]];
    [self.view addSubview:imageview];
    [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(SV).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    
    [SV addSubview:self.tableView];
    self.tableView.separatorStyle = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.manager = [CoreDataManager defaults];
    
    // 删除按钮
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    //创建音心情数组
    self.soundArr = [self lookSound];
    
    [self initnil];
    
}
//重写系统的编辑按钮初始化方法
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}
// 设置哪些可以编辑默认都可以
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
//修改cell的编辑模式默认是删除.还可以进行添加等操作
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

// 实现删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (indexPath.section == 0) {
            
    
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"WriteMood"];
        WriteMood *mood = self.writeArr[indexPath.row];
        NSPredicate *dicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@== %@", @"title", @"%@"], mood.title];
        
        request.predicate = dicate;
        
        NSSortDescriptor *tor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
        [request setSortDescriptors:[NSArray arrayWithObjects: tor, nil]];
        
        NSError *error;
        
        NSArray *arr = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
        for (WriteMood *mood in arr) {
            [self.manager.managedObjectContext deleteObject:mood];
        }
        
        [self.manager saveContext];
        
        [self.writeArr removeObjectAtIndex:indexPath.row];
        
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }else{
            //删除文件
            Sound *model = self.soundArr[indexPath.row];

            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
            NSString *path = [sandBoxPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf",model.name]];
            NSFileManager *manager = [NSFileManager defaultManager];
            [manager removeItemAtPath:path error:nil];
            //删除数据库内容
            
            for (Sound *temp in self.soundArr) {
                if ([temp.name isEqualToString:model.name]) {
                    [self.manager.managedObjectContext deleteObject:temp];
                }
            }
            
            [self.manager saveContext];

            self.soundArr = [self lookSound];
            

            //刷新tableView
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

        }
        
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
       return HEIGHT / 13;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.writeArr.count + self.soundArr.count < 1 ) {
        _nilview.hidden = NO;
    }else{
        _nilview.hidden = YES;
    }
    if (section == 0) {
        return self.writeArr.count;
    }else {
        return self.soundArr.count;
    }
}
- (void)initnil{
    if (!_nilview) {
        _nilview = [[UIView alloc]initWithFrame:self.tableView.frame];
        _nilview.backgroundColor = [UIColor whiteColor];
        [SV addSubview:_nilview];
        UIImageView *aimageView = [[UIImageView alloc]init];
        [_nilview addSubview:aimageView];
        [aimageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(100, 100));
            make.center.equalTo(_nilview);
        }];
        
        aimageView.image = [UIImage imageNamed:@"hezi"];
    }
    UILabel *label = [[UILabel alloc]init];
    [_nilview addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.and.left.equalTo(_nilview);
        make.height.mas_equalTo(20);
        make.centerY.equalTo(_nilview).offset(-120);
    }];
    label.textAlignment = 1;
    label.text = @"心情空空";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        WriteMood *mood = self.writeArr[indexPath.row];
        static NSString *reuse = @"reuse";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
            
        }
        cell.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:.5];
        cell.textLabel.text = mood.title;
        return cell;
    }else {
        static NSString *reuse = @"reuse";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        cell.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:.5];
        Sound *model = self.soundArr[indexPath.row];
        //将时间搓换成时间
        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSLog(@"%@",model.name);
        
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:[model.name doubleValue]/1000];
        NSString * dateString = [formatter stringFromDate:date];
        NSLog(@"%f",[model.name doubleValue]);
        
        cell.textLabel.text = dateString;
        
        return  cell;
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
        return 2;
   
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        WriteMood *mood = self.writeArr[indexPath.row];
        MyWriteMoodViewController *mwmVC = [[MyWriteMoodViewController alloc] init];
        [self.navigationController pushViewController:mwmVC animated:YES];
        mwmVC.title = mood.title;
        mwmVC.str = mood.label;
        
        
    }else {
      
        MySoundMoodViewController *msmVC = [[MySoundMoodViewController alloc] init];
        Sound *model = self.soundArr[indexPath.row];
        msmVC.path = model.name;
        [self.navigationController pushViewController:msmVC animated:YES];
    }
    
}
//  写分区标题高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.writeArr.count == 0 && self.soundArr.count == 0) {
        return 0;
    }else {
        return 30;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    
    if (section == 0) {
        if (!self.writeArr.count >0) {
            return @"没有写心情";
        }
    return @"Write";
    }else {
        if (!self.soundArr.count >0) {
            return @"没有音心情";
        }
    return @"Sound";
    }
}

//发现音心情数组
- (NSArray *)lookSound{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Sound"];
    //    添加约束  谓词
    NSError *error;
    NSArray *arr = [[self.manager managedObjectContext] executeFetchRequest:request error:&error];

    return arr;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
